#!/bin/bash

#  rm daemon.sh -f ; wget  http://wuyou.run/scripts/deploy/daemon.sh ;chmod 750 daemon.sh
#  开机启动&手动运行:  ./daemon.sh boot "8000" "cd /root;/usr/bin/python3 -m http.server 8000 &" & 
#  定时任务: */30 * * * * /opt/daemon.sh cron "8000" "cd /root;/usr/bin/python3 -m http.server 8000 &" & 



Port=$2
Run_CMD=$3

##### kill daemon历史进程 #####
# pkill daemon.sh 

##### 安装netstat #####
which netstat  >/dev/null
if [ $? -ne 0 ];then
 yum install net-tools -y
fi

##### 检测服务端口 #####
function CheckPort(){
  PORT_NUM=$(sudo netstat -pntl |grep ${Port} |wc -l)
  if [ ${PORT_NUM} -eq 0 ];
  then
    return 1
  else
    return 0
  fi
}

##### 判断执行启动命令 #####
function RunProcess(){
  CheckPort $Port
  if [ $? -ne 0 ];then
    sleep 30 #  等待告警抛出异常

    eval "${Run_CMD}" # 字符串解析成命令
    ProcessPID=$(sudo netstat -pntl|grep  ${Port}|awk '{print $7}' |awk -F '/'  '{print $1}')
    echo "${Port} restart in `date +%Y%m%d_%H%M%S`,new pid:${ProcessPID}" >> "/tmp/server_restart`date +%Y%m`.log"
    
  fi
}





function Boot(){
while true
do
  RunProcess "$Port"  "$Run_CMD"
  sleep 120
done
}

function Cron(){
   RunProcess "$Port"  "$Run_CMD"
}


case "$1" in
  "cron"|"CRON")
   cron
   ;;
   "boot"|"BOOT")
   Boot
   ;;
esac




